package cn.jisol.ngame.client;


import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public abstract class QueueNClient extends NClient {

    private Queue<byte[]> sQueue;
    private Thread qThread;

    private boolean isClose = false;

    public QueueNClient(String id) {
        super(id);
        this.sQueue = new LinkedBlockingQueue<>();

        qThread = new Thread(() -> {
            byte[] sMessage = null;
            while (Objects.nonNull((sMessage = sQueue.poll()))){
                this.onMessage(sMessage);
            }
            //如果消息发送完则判断是否关闭
            if(isClose) this.onClose();
        });
    }

    @Override
    public void onSendMessage(byte[] bytes) {
        this.sQueue.add(bytes);
        this.onEnable();
    }

    protected void onEnable(){
        if(Objects.nonNull(qThread) && qThread.isAlive()) return;
        qThread = new Thread(() -> {
            byte[] sMessage = null;
            while (Objects.nonNull((sMessage = sQueue.poll()))){
                this.onMessage(sMessage);
            }
            //如果消息发送完则判断是否关闭
            if(isClose) this.onClose();
        });
        qThread.start();
    }

    protected abstract void onMessage(byte[] bytes);
    protected abstract void onClose();

    @Override
    public void Close() {
        this.isClose = true;
        this.onEnable();
    }
}
